package cn.cellcom.agent.biz;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.common.AgentConstant.CRM_ADD_TYPE;
import cn.cellcom.agent.entity.TSettingEntity;
import cn.cellcom.agent.online.client.IDManager;
import cn.cellcom.agent.pojo.TCrm;
import cn.cellcom.agent.pojo.TCrmField;
import cn.cellcom.agent.pojo.TCrmFieldOption;
import cn.cellcom.agent.pojo.TOrg;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TCrmForm;
import cn.cellcom.agent.struts.form.VisitorForm;
import cn.cellcom.agent.util.RedisManager;
import cn.cellcom.agent.util.ThirdCallbackUtils;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.reflect.ToString;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;
import net.sf.json.JSONObject;

public class TCrmBiz extends AbstractBiz {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public List delete(HttpServletRequest req, ActionForm form, Object obj) {

		return null;
	}

	@Override
	public Object add(HttpServletRequest req, ActionForm form, Object obj) {
		TCrmForm fm = (TCrmForm) form;
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		try {
			log.info("add log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getId();
			// 你必须修改这里的id值
			if (key != null && this.getDao().myGet(TCrm.class, key) != null) {
				return "该记录已经存在，不要重复添加";
			}
			TCrm crm = new TCrm();
			// 以下为pojo的必填字段
			CopyUtil.copy(req, crm, null, false);
			crm.setOrg(user.getOrg());
			crm.setId(IDManager.getCid());
			crm.setCreateTime(System.currentTimeMillis());
			crm.setType(CRM_ADD_TYPE.SYSTEM.ordinal());
			crm.setSex(1);
			crm.setLevel(1);
			crm.setStatus(0);
			this.getDao().mySave(crm);

			return crm;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "新增数据出现错误", e);
		}
	}

	@Override
	public Object modify(HttpServletRequest req, ActionForm form, Object obj) {
		TCrmForm fm = (TCrmForm) form;
		LogonSession ls = new LogonSession(req);
		try {
			log.info("modify log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getId();
			TCrm pojo = (TCrm) this.getDao().myGet(TCrm.class, key);
			if (pojo == null) {
				return "修改的记录不存在";
			}
			log.info("被修改的pojo：" + ToString.toString(TCrm.class, pojo, false));

			// 以下为pojo的必填字段
			CopyUtil.copy(req, pojo, null, false);
			// 以下为pojo的非必填字段

			this.getDao().myUpdate(pojo);

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "修改数据出现错误", e);
		}

	}

	/**
	 * 获取单个crm
	 * 
	 * @param crmId
	 * @return
	 * @throws MyException
	 */
	public TCrm getCrm(String crmId) throws MyException {
		return (TCrm) this.getDao().myGet(TCrm.class, crmId);
	}

	public TCrm getCrmByTid(String tid) throws MyException {
		return (TCrm) this.getDao().myGet("from " + TCrm.class.getSimpleName() + " where tid = ?", new String[] { tid });
	}

	/**
	 * 创建
	 * 
	 * @param cid
	 * @param org
	 * @param pid
	 * @param type
	 * @return
	 * @throws MyException
	 */
	public TCrm createCrm(String cid, String org, String pid, String tid, CRM_ADD_TYPE type) throws MyException {
		if (StringUtils.isBlank(cid)) {
			cid = IDManager.getCid();
		}
		TCrm crm = new TCrm();
		crm.setId(cid);
		crm.setCreateTime(System.currentTimeMillis());
		crm.setName(RedisManager.getInstance().getCrmNo(org));
		crm.setOrg(org);
		crm.setTid(tid);
		crm.setType(type.ordinal());
		crm.setSex(1);
		crm.setLevel(1);
		crm.setStatus(0);
		this.getDao().mySave(crm);
		return crm;
	}

	/**
	 * 获取企业的配置crm字段
	 * 
	 * @param org
	 * @return
	 * @throws MyException
	 */
	public List<TCrmField> getEnableCrmField(String org) throws MyException {
		String hql = "from " + TCrmField.class.getSimpleName() + " where org=? and fenable=? order by ind";
		List list = this.getDao().myList(hql, new Object[] { org, 1 });
		if (AU.isNotBlank(list)) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < list.size(); i++) {
				TCrmField one = (TCrmField) list.get(i);
				sb.append("'").append(one.getFname()).append("',");
			}
			String ids = sb.substring(0, sb.length() - 1);
			String hql2 = "from " + TCrmFieldOption.class.getSimpleName() + " where fieldFname in (" + ids + ") and org=? order by optionValue";
			List list2 = this.getDao().myList(hql2, new Object[] { org });
			for (int i = 0; i < list2.size(); i++) {
				TCrmFieldOption option = (TCrmFieldOption) list2.get(i);
				for (int j = 0; j < list.size(); j++) {
					TCrmField one = (TCrmField) list.get(j);
					if (one.getFname().equals(option.getFieldFname())) {
						one.getOptions().add(option);
					}
				}
			}

		}
		return list;
	}

	/**
	 * 获取或者创建CRM
	 * 
	 * @param req
	 * @param rep
	 * @param cf
	 * @param org
	 * @param setting
	 * @return
	 * @throws MyException
	 */
	public TCrm getOrCreateCrm(HttpServletRequest req, HttpServletResponse rep, VisitorForm cf, TOrg org, TSettingEntity setting) throws MyException {
		TCrm crm = null;
		// 匿名用户
		if (StringUtils.isBlank(cf.getTid())) {
			String cid = null;
			if(req == null) {
				cid = cf.getCid();
			} else {
				Cookie[] cookies = req.getCookies();
				if (cookies != null) {
					for (int i = 0; i < cookies.length; i++) {
						Cookie cookie = cookies[i];
						if (cookie.getName().equals(cf.getPid() + "-agent.crm.id")) {
							cid = cookie.getValue();
							log.info("[{}] crmId got from cookie", cid);
							break;
						}
					}
				}
	
				if (StringUtils.isBlank(cid)) {
					cid = IDManager.getCid();
					log.info("[{}] crmId created and put it to the cookie.", cid);
	
					Cookie cookie = new Cookie(cf.getPid() + "-agent.crm.id", cid);
					cookie.setMaxAge(604800);
					rep.addCookie(cookie);
				}
			}
			crm = this.getCrm(cid);
			if (crm == null) {
				crm = this.createCrm(cid, org.getOrg(), cf.getPid(), null, AgentConstant.CRM_ADD_TYPE.NICK);
				log.info("[{}] crm object created.", cid);
			} else {
				log.info("[{}] crm object got from db.", cid);
			}
		} else {// 同步TID用户
			if (!IDManager.validate(cf.getTid(), cf.getTimestamp(), setting.getAccessKey(), cf.getTtoken())) {
				log.error("[{}] logon but validate fail.", cf.getTid());
				throw new MyException("鉴权有误[VALIDATE-10001]");
			}
			crm = this.getCrmByTid(cf.getTid());
			if (crm == null) {
				crm = this.createCrm(IDManager.getCid(), org.getOrg(), cf.getPid(), cf.getTid(), AgentConstant.CRM_ADD_TYPE.INTERFACE);
			}

			try {
				// 如果传递了crm信息
				String json = null;
				if (StringUtils.isNotBlank(cf.getTcrm())) {
					json = cf.getTcrm();
					json = URLDecoder.decode(json, "UTF-8");
				} else if (StringUtils.isNotBlank(setting.getCallUrl()) && StringUtils.isNotBlank(setting.getCallMethod())
						&& setting.getCallMethod().contains(AgentConstant.ThirdCallback.crmGet.name())) {
					json = ThirdCallbackUtils.call(AgentConstant.ThirdCallback.crmGet, cf.getTid(), setting.getAccessKey(), setting.getCallUrl(),
							null, null);
				}
				if (StringUtils.isNotBlank(json)) {
					TCrm crm2 = (TCrm) JSONObject.toBean(JSONObject.fromObject(json), TCrm.class);
					CopyUtil.copy(crm2, crm, null, false);
					this.getDao().myUpdate(crm);
				}
			} catch (UnsupportedEncodingException e) {
				log.error("[{}] handle the tcrm fail.", cf.getTid(), e);
			} catch (Exception e) {
				log.error("[{}] handle the tcrm fail.", cf.getTid(), e);
			}
		}
		return crm;
	}
}
